$(function () {
    var couponCache = {};
    /**
     * 初始化抽奖活动列表
     */
    var initCouponTable = function () {
        chinese.sInfo = "共 _TOTAL_ 条";
        chinese.sInfoEmpty = "";
        var table = $('#lotgroupList').DataTable({
            "sort": false,
            "search": false,
            "ajax": {
                "url": "pointsystem/listLottery",
                "type": "GET"
            },
            "aoColumnDefs": [{
                    "targets": 0,
                    "className": 'details-control',
                    "mRender": function (data, type, row) {
                        return '<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>';
                    }
                }, {
                    "targets": 1,
                    "mRender": function (data, type, row) {
                        return row.group_name;
                    }
                }, {
                    "targets": 2,
                    "mRender": function (data, type, row) {
                        return row.state == '1' ? "是" : "否";
                    }
                },
                {
                    "targets": 3,
                    "mRender": function (data, type, row) {
                        var operations = $("#operationHTML").html().replace(/#id/g, row.id);
                        return operations;
                    }
                }],
            "order": [3, 'desc'],
            "oLanguage": chinese,
            "iDisplayLength": 10,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            "sDom": 't<"dt-panelfooter clearfix"lip>',
            "initComplete": function (settings, json) {
                cacheCouponPack(json);
            },
            "rowCallback": function (row, data, index) {
                $(row).data("id", data.id).addClass("cursor-pointer text-muted");
                $(row).data("state", data.state);
            }
        });

        function cacheCouponPack(json) {
            if (json.recordsTotal > 0) {
                // 缓存部门列表
                $.map(json.data, function (cp) {
                    couponCache[cp.id] = cp;
                });
            }
        }
        /**
         * 详情展开/关闭
         */
        $('#lotgroupList tbody').on('click', 'td.details-control', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // 关闭详情
                $(this).html('<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>');
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // 展开详情
                $(this).html('<span class="glyphicons glyphicons-circle_minus text-info cursor-pointer fs14"></span>');
                var id = row.data().id,
                        cp = couponCache[id],
                        detail = '<p class="text-center mt20 mb20">尚无满足条件的抽奖商品</p>';
                var state = row.data().state;
                if (cp.placements === undefined) {
                    var members = [];
                    cp.placements = members;
                    $.get("pointsystem/listLotteryByGroup/" + id, function (res) {
                        if (res.recordsTotal > 0) {
                            for (var i = 0; i < res.recordsTotal; i++) {
                                var ticket = res.data[i];
                                members.push(ticket);
                            }
                            if (cp.eventType === 'USER_REGISTER') {
                                detail = sys.render("#couponPlacementTemplate", cp);
                            } else if (cp.eventType === 'USER_INVEST') {
                                detail = sys.render("#investCouponTemplate", cp);
                            } else {
                                detail = sys.render("#refereeCouponTemplate", cp);
                            }
                        }
                        row.child(detail).show();
                        if (state == '1') {
                            $(".edit_lottery_info").hide();
                        }
                        tr.addClass('shown');
                    }).fail(function () {
                        alert("网络通信错误");
                    });
                } else {
                    if (cp.placements.length > 0) {
                        if (cp.eventType === 'USER_REGISTER') {
                            detail = sys.render("#couponPlacementTemplate", cp);
                        } else if (cp.eventType === 'USER_INVEST') {
                            detail = sys.render("#investCouponTemplate", cp);
                        } else {
                            detail = sys.render("#refereeCouponTemplate", cp);
                        }
                    }
                    row.child(detail).show();
                    tr.addClass('shown');
                }
            }
        });

        $('#couponList tbody').on('click', '.edit', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tid = $(this).data("tid"), btn = $(this);
            location = "pointsystem/lotteryAdd/0/" + tid;
        });
    };
    initCouponTable();
});

function online(id) {
    if (confirm('确定上线抽奖活动？')) {
        $.get("pointsystem/countByLotteryOnline", function (result) {
            if (result.success) {
                alert("抽奖活动已有上线，无法上线!");
                return false;
            } else {
                var data = {
                    id: id
                };
                $.post("pointsystem/onlineLotteryGroup", data, function (res) {
                    if (res.success) {
                        alert("抽奖活动上线成功");
                        location.reload();
                    } else {
                        alert("抽奖活动上线失败：" + res.message);
                        sys.btnStop($btn);
                        sys.closeModal();
                    }
                }).fail(function () {
                    alert("网络通信错误");
                });
            }
        });
    }
    return false;
}

function offline(id) {
    if (confirm('确定下线抽奖活动？')) {
        $.get("pointsystem/offlineLotteryGroup/" + id, function (res) {
            if (res.success) {
                alert("抽奖商品已下线");
                location.reload();
            } else {
                alert("抽奖商品下线失败");
                sys.closeModal();
            }
        }).fail(function () {
            alert("网络通信错误");
            sys.closeModal();
        });
    }
    return false;
}